<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    let list = [
        { id: 1, title: "item-1", pid: null },
        { id: 2, title: "item-2", pid: null },
        { id: 3, title: "item-3", pid: null },
        { id: 4, title: "item-1-1", pid: 1 },
        { id: 5, title: "item-1-2", pid: 1 },
        { id: 6, title: "item-2-1", pid: 2 },
        { id: 7, title: "item-2-2", pid: 2 },
        { id: 8, title: "item-3-1", pid: 3 },
        { id: 9, title: "item-3-2", pid: 3 },
        { id: 10, title: "item-1-1-1", pid: 4 },
        { id: 11, title: "item-1-1-1", pid: 4 },
    ]

    /* 
        treeList = [
            { id: 1, title: "item-1", pid: null,chilren: [{ id: 4, title: "item-1-1", pid: 1 },{ id: 5, title: "item-1-2", pid: 1 }] },
            { id: 2, title: "item-2", pid: null },
            { id: 3, title: "item-3", pid: null },
        ]
    
    
    */


    function tree(list, pid = null) {
        let treeList = [];

        for (var i = 0; i < list.length; i++) {
            let item = list[i];
            if (item.pid == pid) {
                let childList = tree(list, item.id);
                if (childList.length) {
                    item.children = childList;
                }
                treeList.push(item);
            }
        }
        return treeList;
    }


    console.log(tree(list));
    console.log(JSON.stringify(tree(list)));

</script>

</html>